﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using PServiceBus.Core.Runtime.Transports;

namespace PServiceBus.Core.Runtime.Messages {
    [Serializable]
    public abstract class BaseMessage : IMessage {

        [MessageShark.MessageSharkIgnore]
        private readonly object _lockObject = new object();

        public BaseMessage() : this(TransportMessage.Empty) { }

        public BaseMessage(TransportMessage message) : this(message, Guid.Empty) { }

        public BaseMessage(Guid topicID) : this(TransportMessage.Empty, topicID) { }

        public BaseMessage(TransportMessage message, Guid topicID) : this(message, new List<MessageResponse>(), topicID) { }

        public BaseMessage(BaseMessage message) : this(message.Message, message.Responses, message.ID, message.TopicID) { }

        public BaseMessage(TransportMessage message, IList<MessageResponse> responses, Guid topicID) : this(message, responses, Guid.NewGuid(), topicID) { }

        public BaseMessage(TransportMessage message, IList<MessageResponse> responses, Guid id, Guid topicID) {
            ID = id;
            Message = message;
            Responses = responses;
            CreateDate = DateTime.Now;
            TopicID = topicID;
        }

        /// <summary>
        /// Gets or sets the responses returned when message was processed.
        /// It contains response for each subscriber that received the message
        /// </summary>
        /// <value>The responses.</value>
        public IList<MessageResponse> Responses { get; set; }

        /// <summary>
        /// Added response in a thread-safe manner
        /// </summary>
        /// <param name="response"></param>
        public void AddResponse(MessageResponse response) {
            lock (_lockObject)
                Responses.Add(response);
        }

        #region IMessage Members

        public TransportMessage Message { get; set; }

        public DateTime CreateDate { get; set; }

        public Guid TopicID { get; set; }

        #endregion

        #region IObject Members

        public Guid ID { get; set; }

        #endregion
    }
}
